#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>

#define MAXLINE 1024

int main() {
    // 创建socket对象
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        return 1;
    }

    // 创建网络通信对象
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(1324);
    addr.sin_addr.s_addr = INADDR_ANY;

    // 绑定socket对象与通信链接
    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind failed");
        return 1;
    }

    struct sockaddr_in cli;
    socklen_t len = sizeof(cli);

    while (1) {
        char buf[MAXLINE];
        ssize_t n = recvfrom(sockfd, buf, MAXLINE, 0, (struct sockaddr*)&cli, &len);
        if (n < 0) {
            perror("接收失败");
            break;
        }
        buf[n] = '\0';
        printf("接收到的客户端消息：: %s\n", buf);

        char reply[] = "Message received";
        if (sendto(sockfd, reply, strlen(reply), 0, (struct sockaddr*)&cli, len) < 0) {
            perror("发送失败");
            break;
        }
    }

    close(sockfd);

    return 0;
}
